# -*- encoding: utf-8 -*-
import webapp2
import logging
import wsgiref.handlers
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers
import urllib
import json
import settings
from google.appengine.ext import db

class MainPage(webapp2.RequestHandler):
    def get(self, token):
        if (token in settings.TOKENS):
            files = blobstore.BlobInfo.gql("")
        
            self.response.headers['Content-type'] = 'text/plain'

            file_list = []

            for fi in files:
                logging.error(fi.filename)
                logging.error(fi.filename)

                f = db.GqlQuery("SELECT * from File where name='%s'" % 
                        fi.filename)[0]
                file_list.append({'name': fi.filename,
                                  'url':  "/serve/%s" % fi.filename,
                                  'downloaded': f.downloaded,
                                  'size': f.size,
								  'odir': f.odir})

            self.response.out.write(json.dumps(file_list))
        else:
            logging.error("Unauthorized action!")
            self.response.out.write('Not Authenticated!')


class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler):
    def get(self, resource, token):
        if (token in settings.TOKENS):
            resource = str(urllib.unquote(resource))

            fi = db.GqlQuery("SELECT * from File where name='%s'" % 
                             resource)[0]
            fi.downloaded = True
            fi.put()
    
            blob_info = blobstore.BlobInfo.gql("", filename = resource)[0]
            
            self.send_blob(blob_info)
        else:
            self.response.out.write("Not Authenticated")

    
app = webapp2.WSGIApplication([
  ('/list/([^/]+)?', MainPage),
  ('/serve/([^/]+)?/([^/]+)?', ServeHandler),
], debug=True)
wsgiref.handlers.CGIHandler().run(app)

